from random import randint

from django.conf import settings
from django.shortcuts import render

# Create your views here.
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from meiduo.libs.yuntongxun.sms import CCP
from threading import Thread
from celery_tasks.sms.tasks import send_sms_code
from users.models import User
from .serializers import UserSerializer, UserDetailSerializer, UserUpdateSerializer
from rest_framework.permissions import IsAuthenticated
from itsdangerous import TimedJSONWebSignatureSerializer as TJS



# 发送短信的方法
# def send_sms_code(mobile, sms_code):
#     ccp = CCP()
#     ccp.send_template_sms(mobile, [sms_code, '5'], 1)


class SMS_CODEView(APIView):

    def get(self, request, mobile):

        # 生成6位短信验证码
        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)
        # 建立连接redis缓存对象
        conn = get_redis_connection('sms_codes')
        # 判断有限期的中间依据
        flag =conn.get('sms_code_flag_%s' % mobile)
        if flag:
            return Response({'error': '发送过于频繁'}, status=400)

        pl = conn.pipeline()    # 生成管道对象. 管道可以让多条请求缓存只请求一次
        # string: setex(key-time-value)
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        # 有限期为60秒,
        pl.setex('sms_code_flag_%s' % mobile, 60, 1)
        pl.execute()    # 连接缓存,写入指令
        # 发送短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, '5'], 1)
        # 进程
        # t = Thread(target='send_sms_code', kwargs={'mobile': mobile, 'sms_code': sms_code})
        # t.start()
        # t.join()
        # 使用celery,delay异步发送短信
        send_sms_code.delay(mobile, sms_code)

        return Response({'message': 'OK'})


class UserNameView(APIView):

    def get(self, request, username):
        count = User.object.filter(username=username).count()
        return Response({
            'count':count,
        })


class MobileView(APIView):

    def get(self, request, mobile):
        count = User.object.filter(mobile=mobile).count()
        return Response({
            'count':count,
        })


class UsersView(CreateAPIView):
    """
        注册用户数据
    """
    serializer_class = UserSerializer


class UserDetailView(RetrieveAPIView):

    serializer_class = UserDetailSerializer
    permission_classes = [IsAuthenticated]      # 权限指定,认证的用户可看

    # 重写get_object方法,指定返回对象
    def get_object(self):
        print(self.request.user)
        return self.request.user


class UserEmailView(UpdateAPIView):

    serializer_class = UserUpdateSerializer

    # 重写get_object方法,指定返回对象
    def get_object(self):
        print(self.request.user)
        return self.request.user


class EmailVerifyView(APIView):

    """
    验证用户邮箱
    """
    def get(self, request):
        # 1. 获取前端数据
        token = request.query_params.get('token')
        # 2. 验证数据,解密token
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(token)
        except:
            return Response({'errors': 'token值无效'})

        # 3. 查询用户
        username = data.get('name')
        try:
            user = User.objects.get(username=username)
        except:
            return Response({'errors': '用户不存在'})

        # 4. 更新用户邮箱验证状态
        user.email_active = True
        user.save()
        # 5. 返回结果
        return Response({'message': True})



